package spring.config;

import java.util.Properties;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration		//声明当前类是一个配置类
@ComponentScan("edu.yuhf")		//指定扫描的包。
@EnableTransactionManagement		//开启事务控制
@PropertySource("classpath:jdbc.properties")		//加载jdbc.properties文件
public class DataSourceConfig {

	@Resource
	Environment env;
	
	@Resource(name="dataSource")
	private DruidDataSource dataSource;
	
	@Resource(name="sessionFactory")
	SessionFactory sessionFactory;
	
	//为应用程序配置数据库连接，配置完之后就放入应用程序上下文。
	@Bean(name="dataSource")
	public DruidDataSource getBruidDataSource(){
		DruidDataSource dds=new DruidDataSource();
		dds.setUrl(env.getProperty("jdbc.url"));
		dds.setUsername(env.getProperty("jdbc.username"));
		dds.setPassword(env.getProperty("jdbc.password"));
		dds.setDriverClassName(env.getProperty("jdbc.class_name"));
		return dds;
	}
	/*
	@Bean(name="jdbcTemplate")
	public JdbcTemplate getJdbcTemplate(){
		JdbcTemplate jdbcTemplate=new JdbcTemplate();
		jdbcTemplate.setDataSource(dataSource);
		return jdbcTemplate;
	}*/
	
	@Bean(name="sessionFactory")
	public LocalSessionFactoryBean getLocalSessionFactoryBean(){
		LocalSessionFactoryBean lsfb=new LocalSessionFactoryBean();
		lsfb.setDataSource(dataSource);		//配置数据源
		lsfb.setPackagesToScan("edu.yuhf.entity");	//指定entity文件所在的包
		//加载hibernate的配置信息，这里就相当于hibernate.cfg.xml文件。
		Properties prop=new Properties();
		prop.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle9Dialect");
		prop.setProperty("hibernate.current_session_context_class", "org.springframework.orm.hibernate4.SpringSessionContext");
		prop.setProperty("show_sql", "true");
		lsfb.setHibernateProperties(prop);
		return lsfb;
	}
	
	@Bean(name="transactionManager")
	public HibernateTransactionManager getDataSourceTransactionManager(){
		HibernateTransactionManager htm=new HibernateTransactionManager();
		htm.setSessionFactory(sessionFactory);
		return htm;
	}
}

